package com.wandian.setting.mvvm.usersetting;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;

import androidx.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import android.util.Log;
import android.view.Gravity;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.UserInfoBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.BitMapUtils;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.GlideUtil;
import com.mylib.libcore.utils.MyGlideEngine;
import com.mylib.libcore.utils.StatusBarUtils;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.widget.SelectPopupWindow;
import com.mylib.widget.datetimepicker.DateTimePicker;
import com.wandian.setting.R;
import com.wandian.setting.databinding.SetActivityUserSettingBinding;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.io.File;
import java.util.Date;
import java.util.List;

import static com.mylib.libcore.config.AppConfig.CHOOSE_PHOTO;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description  个人资料
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_SETTING_USER_SETTING)
public class UserSettingActivity extends  BaseMVVMActivity<UserSettingViewModel>  {
    private SetActivityUserSettingBinding dataBinding;
    //自定义的弹出框类
    private SelectPopupWindow menuWindow;
    //弹框类型
    private String type;
    //选择相册
    private static final int CHOOSE_PHOTO = 155;
    //权限回调
    private static final int PERMISSIONCODE = 66;

    //图片压缩地址
    private String compressImgPath;
    //用户信息
    private UserInfoBean userInfoBean;


    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.set_activity_user_setting);
        dataBinding.setLifecycleOwner(this);
        StatusBarUtils.with(this,false)
                .setIsActionBar(false)
                .clearActionBarShadow()
                .setDrawable(getResources().getDrawable(R.drawable.sys_color))
                .init();
        userInfoBean = AppContext.getInstance().getAppPreferencesHelper().getUserInfoBean();
        dataBinding.bindToolBar.toolBarTvTitle.setText("个人资料");
        dataBinding.setViewModel(mViewModel);
        initClink();
        initViewData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mViewModel.getUserInfo();
    }

    private void initClink(){
        //修改头像
        dataBinding.rlUserHead.setOnClickListener(v -> initCamer());
        //修改昵称
        dataBinding.bindName.rlNextPage.setOnClickListener(v ->   ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_SETTING_MODIFY_USER_NAME).navigation());
        // 修改性别
        dataBinding.bindSex.rlNextPage.setOnClickListener(v -> showDowloadSureDialog("sex"));
        // 个人简介
        dataBinding.bindJj.rlNextPage.setOnClickListener(v -> ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_SETTING_EDIT_BRIEF).navigation());
        //返回页面
        dataBinding.bindToolBar.toolBarIvBack.setOnClickListener(v ->  finish());
    }

    private void initViewData(){
        //刷新用户信息
        mViewModel.userBean.observe(this,userBean->{
            if(!UIUtils.isEmpty(userBean)){
                this.userInfoBean = userBean;
                notifyMineUI();
            }
        });

        mViewModel.oosBean.observe(this,oosBean->{
            if(!UIUtils.isEmpty(oosBean)){
                mViewModel.upLoadImg(this,dataBinding.ivUserHead,oosBean,  compressImgPath);
            }else {
                ToastUtil.show("图片上传失败");
            }
        });

        notifyMineUI();
    }

    private void notifyMineUI(){

        //头像
        if(!UIUtils.isEmpty(userInfoBean.getHeadPic())) GlideUtil.intoHeadImg(this,userInfoBean.getHeadPic(),dataBinding.ivUserHead);
        //昵称
        dataBinding.bindName.tvLeft.setText("昵称");
        dataBinding.bindName.tvRight.setText(userInfoBean.getNickName()+"");
        //性别
        dataBinding.bindSex.tvLeft.setText("性别");
        if(userInfoBean.getSex()==0){
            dataBinding.bindSex.tvRight.setText("未知");
        }else {
            dataBinding.bindSex.tvRight.setText(userInfoBean.getSex()==1?"男":"女");
        }

        //用户等级
        dataBinding.bindLevel.tvLeft.setText("等级");
        dataBinding.bindLevel.tvRight.setText( "lv-1");
        //个人简介
        dataBinding.bindJj.tvLeft.setText("个人简介");
        dataBinding.bindJj.tvRight.setText(userInfoBean.getDescription()+"");
    }

    public void showDowloadSureDialog(String type) {
        this.type = type;
        menuWindow = new SelectPopupWindow(getContext(), itemsOnClick,type);
        //显示窗口
        //设置layout在PopupWindow中显示的位置
        menuWindow.showAtLocation(dataBinding.llUserInfo, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){
        public void onClick(View v) {
            menuWindow.dismiss();
            int i = v.getId();
            if (i == R.id.tv_choose_one) {
                if(!UIUtils.isEmpty(type)){
                    if(type.equals("sex")){
                        mViewModel.modifySex("1");//1男
                        dataBinding.bindSex.tvRight.setText("男");
                    }
                }
            }
            if (i == R.id.tv_choose_two) {
                if(!UIUtils.isEmpty(type)){
                    if(type.equals("sex")){//0女
                        mViewModel.modifySex("0");
                        dataBinding.bindSex.tvRight.setText("女");
                    }
                }
            }
        }
    };

    //修改头像
    private void initCamer() {
        boolean isAllGranted = checkPermissionAllGranted(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_SETTINGS});
        if (isAllGranted) {
            choosePhoto();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_SETTINGS}, PERMISSIONCODE);
        }
    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONCODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                choosePhoto();
            }
        }
    }

    //相册
    private void choosePhoto() {
        Matisse.from(this)
                .choose(MimeType.ofAll()) // 选择 mime 的类型
                .countable(true)
                .maxSelectable(1) // 图片选择的最多数量
                .originalEnable(false)
                .maxOriginalSize(5)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                .theme(R.style.Matisse_Dracula)
                .capture(true) //是否提供拍照功能
                .autoHideToolbarOnSingleTap(true)
                .captureStrategy(new CaptureStrategy(true, mContext.getPackageName() + ".provider"))//存储到哪里
                .forResult(CHOOSE_PHOTO);// 设置作为标记的请求码
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("requestCode",requestCode+"="+resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == CHOOSE_PHOTO) {
                if (!UIUtils.isEmpty(data)) {
                    List<Uri> mSelected = Matisse.obtainResult(data);
                    Bitmap bitmap = BitMapUtils.getBitmapFromUri(this, mSelected.get(0));
                    compressImgPath = FileUtil.getCompressFilePath(bitmap);
                    if(!UIUtils.isEmpty(compressImgPath)){
                        mViewModel.getOOSToken();
                    }else {
                        ToastUtil.show("获取本地图片失败");
                    }
                } else {
                    ToastUtil.show("上传图片失败");
                }
            }
        }
    }


}
